package com.gdit.zax.servletjsp;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.BannerPicDao;
import com.gdit.zax.dao.CourseDao;
import com.gdit.zax.dao.DynamicDao;
import com.gdit.zax.dao.UpLoadDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.dao.VideoDao;
import com.gdit.zax.entitys.AddVideo;
import com.gdit.zax.entitys.BaseEntity;
import com.gdit.zax.entitys.Course;
import com.gdit.zax.entitys.Dynamic;
import com.gdit.zax.entitys.Section;
import com.gdit.zax.entitys.Tag;
import com.gdit.zax.entitys.UpLoad;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.entitys.VideoInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.FFMPEtool;
import com.gdit.zax.utils.FromRequest;
import com.gdit.zax.utils.Repost;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.WebUpload;
import com.gdit.zax.utils.webUtil;

/**
 * 提交视频信息
 * @author lenovo
 *
 */
public class PostPubVideo extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		FromRequest newrequest = new FromRequest(getServletContext(), request, response);
		
		String token = webUtil.getCookie(request, "LoginCookie");
		String flag = newrequest.getParameterString("flag");
		
		String coursename = newrequest.getParameterString("coursename");
		int coursetype = TextUtil.String2int(newrequest.getParameterString("coursetype") ,-1) ;//选择的视频分类
		String coursecontent = newrequest.getParameterString("coursecontent");
		String coursepic;//章节图片路径
		FileItem coursepicfile = (FileItem) newrequest.getParameter("coursepic");
		
		String sectionname = newrequest.getParameterString("sectionname");
		String sectiontype = newrequest.getParameterString("sectiontype") ;//选择的课程分类
		String sectioncontent = newrequest.getParameterString("sectioncontent");
		
		String videoname = newrequest.getParameterString("videoname");
		String videotype = newrequest.getParameterString("videotype") ;//选择的视频分类
		String videocontent = newrequest.getParameterString("videocontent");
		
		String tagsstr = newrequest.getParameterString("tag");

		
		
		if (coursetype==-1) {
			Repost.message("请选择视频分类!", request, response);
			return;
		}
		
		Connection conn = DBUtil.getConnection();
		if (conn == null) {
			Repost.dberror(request, response);
			return;
		}
		
		DAOFactory dao = DAOFactory.init(conn, request, response);
		UserDao udao = dao.getUserDao();
		UpLoadDao updao = dao.getUploadDao();
		VideoDao vdao = dao.getVideoDao();
		DynamicDao ddao = dao.getDynamicDao();
		CourseDao cdao = dao.getCourseDao();
//		ddao.addVideoDynamic(userid, dym)

		
		UserInfo user = udao.getInfo(Constant.LOGINTYPE_WEB, token);
		if (user==null) {
			Repost.nologin(response);
			return;
		}
		
		Course cr = cdao.getCourseByName(coursename);
		if (cr != null) {
			if (cr.getAnthorid() != user.getId()) {
				Repost.message("该课程已经被其他用户占用，请更换课程名称!", request, response);
				return;
			}
		}
		
		if (user.getUlevel()<Constant.ULEVEL_teacher) {
			Repost.message("你还没有权限操作!", request, response);
			return;
		}
		
		UpLoad uploadinfo =updao.getUplodaInfo(flag);
		if (uploadinfo==null) {
			Repost.message("你还没上传视频!", request, response);
			return;
		}
		
		if (TextUtil.isEmpty(uploadinfo.getFilename())) {
			Repost.message("不能上传空视频哦!", request, response);
			return;
		}
		
		
		//=================开始操作
		String rootpath = getServletContext().getRealPath("/");
		
		String oldfilepath = rootpath + uploadinfo.getFilepath();
		File ofile = new File(oldfilepath);
		
		String newfilepath = rootpath + File.separator + "videos"  + File.separator  + ofile.getName();
		File nfile = new File(newfilepath);
		
		String picfilepath = rootpath + File.separator + "videopics" + File.separator + System.currentTimeMillis() + ".jpg";
		File pfile = new File(picfilepath);
		//移动文件
		
		if (!ofile.renameTo(nfile)) {
			Repost.message("文件操作过程中出错!", request, response);
			return;
		}
		
		//缩略图生成
		int resu = FFMPEtool.getPicFromVideo(newfilepath, picfilepath);
		if (resu == FFMPEtool.ERROR_Encoder) {
			Repost.message("解码错误,请注意文件格式!", request, response);
			return;
		} else if (resu==FFMPEtool.ERROR_NOEXIST_sourcefile) {
			Repost.message("上传文件失败!", request, response);
			return;
		} else if (resu==FFMPEtool.ERROR_NOEXIST_targetpic) {
			Repost.message("生成缩略图失败!", request, response);
			return;
		} else if (resu==FFMPEtool.ERROR_YOUCODE) {
			Repost.message("系统出错，请联系管理员!", request, response);
			return;
		}
		
			
		AddVideo ainfo = new AddVideo();
		
		ainfo.setUserid(user.getId());
		
		
		//课程数据
		
		Course course = cdao.getCourseByName(coursename);
		if (course == null) course = new Course();
		BaseEntity ctype = new BaseEntity();
		
		course.setAnthorid(user.getId());
		course.setName(coursename);
		course.setIntroduction(coursecontent);
		ctype.setId(coursetype);
		
		//章节图片处理
		if (coursepicfile != null && !"".equals(coursepicfile.getName())) {//选择了图片
			coursepic = System.currentTimeMillis() + "." + WebUpload.getExtensionName(coursepicfile.getName());
			if (WebUpload.save(getServletContext(), coursepicfile, "videopics", coursepic)){
				course.setPic("videopics/" + coursepic);
			}
		}
		if (course.getPic() == null || "".equals(course.getPic())) {
			course.setPic("videopics/" + pfile.getName());
		}

		ainfo.setCourse(course);
		ainfo.setCoursetype(ctype);

		
		
		//章节数据
		Section section = new Section();
		BaseEntity stype = new BaseEntity();
		
		section.setAnthorid(user.getId());
		section.setIntroduction(sectioncontent);
		section.setName(sectionname);
		stype.setName(sectiontype);
		
		ainfo.setSection(section);
		ainfo.setSectiontype(stype);
		

		
		
		//视频数据
		VideoInfo video = new VideoInfo();
		BaseEntity vtype = new BaseEntity();
		
		video.setAnthorId(user.getId());
		video.setName(videoname);
		video.setIntroduction(videocontent);
		vtype.setName(videotype);
		
		video.setUrl("videos/"  + nfile.getName());
		video.setPic("videopics/" + pfile.getName());
		
		ainfo.setVideo(video);
		ainfo.setVideotype(vtype);
		
		//标签数据
		String[] tagss = tagsstr.split(";");
		ArrayList<Tag> tags = new ArrayList<Tag>();
		for (String str:tagss) {
			Tag tag = new Tag();
			tag.setName(str);
			tags.add(tag);
		}
		ainfo.setTags(tags);
		
		
		//开始添加
		if (vdao.addVideo(ainfo)){
			//更新视频动态
			Dynamic dym = new Dynamic();
			dym.setContent("发布了视频");
			dym.setDyntype(Constant.DYNAMICSYS_publicvideo);
			ddao.addVideoDynamic(user.getId(), dym);
			Repost.message("发布视频成功!", request, response);
		} else {
			Repost.message("发布视频失败!", request, response);
		}

	}

}
